package com.chinasoft.api;

import com.chinasoft.pojo.ElectronicsSales;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

        public class HdfsApi {

            public List<ElectronicsSales> getElectronicsSalesList() throws Exception {
                List<ElectronicsSales> list = new ArrayList<>();

        Configuration conf = new Configuration(true);
        FileSystem hdfs = FileSystem.get(conf);
        Path path = new Path("hdfs://hn41:8020/dashuju/dashuju.csv");

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(hdfs.open(path)))) {

            String line;
            br.readLine();          // 跳过表头（id,event_time,...）

            while ((line = br.readLine()) != null) {
                if (line.trim().isEmpty()) continue;
                String[] arr = line.split(",", -1);

                /* 按 CSV 真实顺序取值 */
                ElectronicsSales es = new ElectronicsSales(
                        parseInteger(arr[0]),      // id
                        arr[1],                    // event_time
                        parseLong(arr[2]),         // order_id
                        parseLong(arr[3]),         // product_id
                        parseLong(arr[4]),         // category_id
                        emptyToNull(arr[5]),       // category_code
                        emptyToNull(arr[6]),       // brand
                        parseBigDecimal(arr[7]),   // price
                        parseLong(arr[8]),         // user_id
                        parseInteger(arr[9]),      // age
                        emptyToNull(arr[10]),      // sex
                        emptyToNull(arr[11])       // local
                );
                list.add(es);
            }
        }
        return list;
    }

    /* ---------- 下面是小工具 ---------- */
    private static Long parseLong(String s) {
        if (s == null || s.trim().isEmpty()) return null;
        // 科学计数法 → double → long
        double d = Double.parseDouble(s.trim());
        return (long) d;
    }

    private static Integer parseInteger(String s) {
        if (s == null || s.trim().isEmpty()) return null;
        double d = Double.parseDouble(s.trim());
        return (int) d;
    }

    private static java.math.BigDecimal parseBigDecimal(String s) {
        return s == null || s.trim().isEmpty() ? null : new java.math.BigDecimal(s.trim());
    }

    private static String emptyToNull(String s) {
        return (s == null || s.trim().isEmpty()) ? null : s.trim();
    }


}
